﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Reflection;
using Jeelu.Attributes;
using NLog;

namespace Jeelu.Data.SQLite.Common
{
    internal class ContextHelper
    {
        private static readonly Logger _Logger = LogManager.GetCurrentClassLogger();

        public static void Fill(Type type, ref Dictionary<string, IDbDataParameter> dbParameters, ref Dictionary<string, PropertyInfo> propertyInfoMap)
        {
            PropertyInfo[] pes = type.GetProperties();
            foreach (PropertyInfo propertyInfo in pes) //获取所有的属性
            {
                try
                {
                    object[] pattrs = propertyInfo.GetCustomAttributes(true); //获取所有的定制特性
                    if (pattrs.OfType<EntityColumnAttribute>().Any()) //如果该属性的定制特性包含指定的特性
                    {
                        EntityColumnAttribute pa = pattrs.OfType<EntityColumnAttribute>().FirstOrDefault();
                        if (pa != null && !String.IsNullOrWhiteSpace(pa.ColumnName))
                        {
                            if (propertyInfoMap.ContainsKey(pa.ColumnName)) continue;
                            propertyInfoMap.Add(pa.ColumnName, propertyInfo);
                            dbParameters.Add(pa.ColumnName, new SQLiteParameter(pa.ColumnName));
                        }
                        else
                        {
                            if (propertyInfoMap.ContainsKey(propertyInfo.Name)) continue;
                            propertyInfoMap.Add(propertyInfo.Name, propertyInfo); //使用属性名作为列名
                            dbParameters.Add(propertyInfo.Name, new SQLiteParameter(propertyInfo.Name));
                        }
                    }
                }
                catch (Exception e)
                {
                    _Logger.WarnException("获取对象的属性的特性时异常。", e);
                }
            }
        }
    }
}